package com.dong;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock加锁
 */
public class Test1 {

    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }).start();


    }
}

class Ticket {

    private int ticket = 50;

    Lock lock = new ReentrantLock();

    public void sale() {

        lock.lock();

        try {
            if (this.ticket > 0) {
                System.out.println("卖一张票，剩余" + (--this.ticket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            lock.unlock();
        }


    }

}
